<template>
  <a-card class="case_produce" :bordered="false">
    <a-spin tip="加载中..." :spinning="spinning">
      <div style="margin-bottom: 15px">
        <span class="add_form_label">{{ labelTitle }}</span>
        <span style="padding-left: 10px" v-if="currentSonstatus != null && currentSonstatus != undefined">
          <a-tag color="#52c41a" style="padding: 0px 5px">
            {{ Tp_proctypeEnum[currentSonstatus].sonStatus.name }}
          </a-tag>
        </span>
        <!-- 非中止情况展示这一个按钮 -->
        <span v-if="operateBtnShow">
          <!-- 终止-调解 ,撤销,告知，受理-其他处理 -->
          <!-- <a-button
            v-if="selectKey == Tp_decisionValue.TERMEDIATE || selectKey == Tp_decisionValue.REVOKE || selectKey == Tp_decisionValue.INFORM || selectKey == Tp_decisionValue.OTHERDEAL"
            @click="startBusinessProcedClick"
            type="primary"
            class="add_form_btn"
            :loading="processLoading">
            {{ btnLabel }}
          </a-button>
          <a-button v-else @click="activeBtnClick" type="primary" class="add_form_btn">
            {{ btnLabel }}
          </a-button> -->

          <a-button
            v-if="btnLabel"
            @click="initCaseInterven"
            type="primary"
            class="add_form_btn btn_primary_color"
            :loading="processLoading"
          >
            {{ btnLabel }}
          </a-button>
        </span>

        <a-button
          v-if="
            this.applyid == $route.params.faapplyid &&
            isEditModel &&
            selectBtnShow &&
            sonStatus.includes('hear_decision')
          "
          @click="changeDecisionType"
          type="primary"
          class="add_form_btn btn_primary_color"
          :loading="processLoading"
        >
          变更决定类型
        </a-button>
        <!-- 新增自定义材料 只在编辑模式中显示 -->
        <a-button
          v-if="isEditModel && uploadBtnShow"
          class="add_form_btn btn_normal_color"
          @click="addCustomerMaterial"
        >
          新增自定义材料
        </a-button>
        <a-divider />
      </div>

      <!-- 级联选择框 -->
      <div style="height: 50px; margin-bottom: 10px">
        <a-col :span="4">
          <span class="tip_label"
            ><span style="color: red; padding-right: 5px"> *</span><span>决定类型：</span></span
          ></a-col
        >
        <a-col :span="18" style="display: flex; justify-content: start; align-items: center; align-items: flex-start">
          <!-- <a-select
            v-model="selectKey"
            @change="(key) => selectChange(key, false)"
            placeholder="请选择"
            style="width: 200px"
            :disabled="!operateBtnShow"
            :allowClear="false"
          >
            <a-select-option v-for="(item, index) in options" :key="index" :value="item.value">
              {{ item.name }}
            </a-select-option>
          </a-select> -->
          <!-- :popupStyle="{'width': '120px'}" -->
          <!-- searchPlaceholder="输入关键字搜索" -->
          <div
            style="color: #40a9ff; font-size: 16px; margin-right: 10px; margin-bottom: 10px; width: 250px"
            class="beyond_hiding"
            :style="`color: ${spanColor}`"
          >
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ selectRootName }}</span>
              </template>
              {{ selectRootName }}
            </a-tooltip>
          </div>
          <a-tree-select
            v-model="selectKey"
            :tree-data="options"
            :show-search="true"
            style="width: 400px; margin-bottom: 10px"
            :dropdown-style="{
              maxHeight: '400px',
              overflow: 'auto'
            }"
            placeholder="请选择"
            searchPlaceholder="输入关键字搜索"
            :replaceFields="{ children: 'children', title: 'name', key: 'id', value: 'id' }"
            @change="key => selectChange(key, false)"
            allowClear
            :disabled="!(isEditModel && selectBtnShow)"
            treeNodeFilterProp="title"
          >
          </a-tree-select>
        </a-col>
      </div>
      <div style="height: 50px; padding-top: 10px">
        <a-col :span="4"> <span class="tip_label">是否市领导审批：</span></a-col>
        <a-col :span="18">
          <a-radio-group
            name="radioGroup"
            v-model="isCitymanager"
            @change="citymanagerChange"
            :disabled="!operateBtnShow"
          >
            <a-radio :value="3200"> 是 </a-radio>
            <a-radio :value="3201"> 否 </a-radio>
          </a-radio-group>
        </a-col>
      </div>

      <a-list class="file_list" item-layout="horizontal" :data-source="fileItem">
        <a-list-item slot="renderItem" slot-scope="item">
          <a-list-item-meta style="margin-top: 10px">
            <span slot="title">
              <div v-if="!item.isCustomer">
                <span
                  v-if="item.required"
                  style="color: red; padding-right: 5px; text-align: center; display: inline-block; height: 32px"
                  >*</span
                >
                <span v-else style="padding-right: 10px"></span>
                <!-- <a-icon class="file_icon" slot="avatar" type="file-text" /> -->
                <div class="file_title">
                  <span class="upload_span">{{ item.fileName }}</span>
                  <a
                    style="color: #0072c6; margin-left: 10px"
                    class="upload_btn btn_normal_color"
                    v-show="uploadBtnShow"
                    @click="showUploadModal(item, false)"
                  >
                    <a-icon type="upload" />上传</a
                  >
                </div>
                <!-- <a-upload
                  :class="uploadBtnShow ? 'upload-style' : 'upload-style-hidden'"
                  :accept="acceptFileType"
                  :data="item"
                  :customRequest="uploadMaterial"
                  :beforeUpload="(file) => beforeUpload(file)"
                  :remove="handleRemove"
                  @preview="fileView"
                  :fileList="item.fileList"
                  :showUploadList="false"
                  name="file"
                  :multiple="true"
                >
                  <a-button v-show="uploadBtnShow"> <a-icon type="upload" />上传</a-button>
                </a-upload> -->
                <div class="upload_list_div" v-for="(fileItem, index) in item.fileList" :key="index">
                  <a class="upload_list_dropdown ant-dropdown-link" @click="e => e.preventDefault()">
                    <a-icon :style="{ color: '#0072c6' }" type="link" style="font-size: 14px" />
                    <a
                      type="link"
                      class="upload_list_item_name beyond_hiding"
                      :title="fileItem.filename"
                      :key="index"
                      @click="fileItem.isEditor ? null : handleClick(fileItem, index)"
                      @dblclick.prevent="handleDoubleClick(fileItem, index)"
                    >
                      <!-- 添加重命名输入框，根据fileItem.isEditor状态显示 -->
                      <input
                        :ref="`input${index}`"
                        v-show="fileItem.isEditor"
                        type="text"
                        class="transparent-input"
                        v-model="newFilename"
                        :key="index"
                        ref="inputRef"
                        autofocus
                        @blur="saveFileName(fileItem)"
                        @keydown.enter="saveFileName(fileItem)"
                      />

                      <span style="color: #0072c6" v-show="!fileItem.isEditor">{{ fileItem.filename }}</span>
                    </a>
                    <a-dropdown :trigger="['click']">
                      <a
                        class="ant-dropdown-link"
                        style="display: inline-block; width: 70px; color: #000"
                        @click="e => e.preventDefault()"
                        >操作<a-icon type="down" style="padding-left: 10px"
                      /></a>
                      <a-menu slot="overlay">
                        <a-menu-item>
                          <a style="display: block" @click="downloadFile(fileItem)">下载</a>
                        </a-menu-item>
                        <!-- <a-menu-item>
                          <a style="display: block;" @click="fileView(fileItem)">预览</a>
                        </a-menu-item> -->
                        <a-menu-item>
                          <a style="display: block" @click="handleRemove(fileItem)">删除</a>
                        </a-menu-item>
                        <!-- <a-menu-item>
                          <a style="display: block;" @click="editFile(fileItem)">编辑</a>
                        </a-menu-item> -->
                        <a-menu-item>
                          <a style="display: block" @click="weboffice(currentUser.userId, applyid, fileItem)"
                            >在线编辑</a
                          >
                        </a-menu-item>
                        <a-menu-item>
                          <a style="display: block" @click="versionView(fileItem)">历史版本</a>
                        </a-menu-item>
                      </a-menu>
                    </a-dropdown>
                  </a>
                </div>
              </div>
              <div v-else-if="item.isSaved && !item.isUpdated">
                <span style="padding-right: 10px"></span>
                <!-- <a-icon class="file_icon" slot="avatar" type="file-text" /> -->
                <div class="file_title">
                  <span class="upload_span">
                    {{ item.fileName }}
                    <a
                      style="color: #0072c6; margin-left: 10px"
                      class="upload_btn btn_normal_color"
                      v-show="uploadBtnShow && item.isSaved"
                      @click="showUploadModal(item, true)"
                    >
                      <a-icon type="upload" />&nbsp;上传</a
                    >
                    <a-divider type="vertical" />
                    <span style="color: #0072c6" @click="editCustomerMaterial(item)">
                      <a-icon
                        v-show="uploadBtnShow"
                        class="customer_icon"
                        @click="editCustomerMaterial(item)"
                        type="edit"
                      />&nbsp;编辑</span
                    >
                    <a-popconfirm
                      title="确认删除自定义材料项及关联文件？"
                      ok-text="是"
                      cancel-text="否"
                      @confirm="deleteCustomer(item)"
                      class="left_icon"
                    >
                      <a-divider type="vertical" />
                      <span style="color: #0072c6">
                        <a-icon v-show="uploadBtnShow" class="customer_icon" type="delete" />&nbsp;删除</span
                      >
                    </a-popconfirm>
                  </span>
                </div>
                <!-- <a-upload
                  :class="uploadBtnShow ? 'upload-style' : 'upload-style-hidden'"
                  :accept="acceptFileType"
                  :data="item"
                  :customRequest="uploadMaterialCustomer"
                  :beforeUpload="(file) => beforeUpload(file)"
                  :remove="handleRemove"
                  @preview="fileView"
                  :fileList="item.fileList"
                  :showUploadList="false"
                  name="file"
                  :multiple="true"
                >
                  <a-button v-show="uploadBtnShow && item.isSaved"> <a-icon type="upload" />上传</a-button>
                </a-upload> -->
                <div class="upload_list_div" v-for="(fileItem, index) in item.fileList" :key="index">
                  <a class="upload_list_dropdown ant-dropdown-link" @click="e => e.preventDefault()">
                    <a-icon :style="{color: '#0072c6'}"  type="link" style="font-size: 14px" />
                    <a
                      type="link"
                      class="upload_list_item_name beyond_hiding"
                      :title="fileItem.filename"
                      :key="index"
                      @click="fileItem.isEditor ? null : handleClick(fileItem, index)"
                      @dblclick.prevent="handleDoubleClick(fileItem, index)"
                    >
                      <!-- 添加重命名输入框，根据fileItem.isEditor状态显示 -->
                      <input
                        :ref="`input${index}`"
                        v-show="fileItem.isEditor"
                        type="text"
                        class="transparent-input"
                        v-model="newFilename"
                        :key="index"
                        ref="inputRef"
                        autofocus
                        @blur="saveFileName(fileItem)"
                        @keydown.enter="saveFileName(fileItem)"
                      />

                      <span style="color: #0072c6" v-show="!fileItem.isEditor">{{ fileItem.filename }}</span>
                    </a>
                    <a-dropdown :trigger="['click']">
                      <a
                        class="ant-dropdown-link"
                        style="display: inline-block; width: 70px;color: #000"
                        @click="e => e.preventDefault()"
                        >操作<a-icon type="down" style="padding-left: 10px"
                      /></a>
                      <a-menu slot="overlay">
                        <a-menu-item>
                          <a style="display: block" @click="downloadFile(fileItem)">下载</a>
                        </a-menu-item>
                        <!-- <a-menu-item>
                          <a style="display: block;" @click="fileView(fileItem)">预览</a>
                        </a-menu-item> -->
                        <a-menu-item>
                          <a style="display: block" @click="handleRemove(fileItem)">删除</a>
                        </a-menu-item>
                        <a-menu-item>
                          <a style="display: block" @click="weboffice(currentUser.userId, applyid, fileItem)"
                            >在线编辑</a
                          >
                        </a-menu-item>
                        <a-menu-item>
                          <a style="display: block" @click="versionView(fileItem)">历史版本</a>
                        </a-menu-item>
                      </a-menu>
                    </a-dropdown>
                  </a>
                </div>
              </div>
              <div class="customer_div" v-else-if="!item.isSaved || item.isUpdated">
                <span class="customer_span"> {{ !item.isSaved ? '新增:' : '修改:' }}</span>
                <a-input
                  class="customer_input"
                  ref="userNameInput"
                  v-model="item.fileName"
                  placeholder="请输入自定义材料名称"
                  :max-length="50"
                >
                  <!-- <a-icon slot="prefix" type="file-add" /> -->
                  <a-tooltip slot="suffix" title="材料名称长度上限50">
                    <a-icon type="info-circle" style="color: rgba(0, 0, 0, 0.45)" />
                  </a-tooltip>
                </a-input>
                <div class="customer_icon_group" v-show="uploadBtnShow">
                  <a-popconfirm
                    title="确认撤销吗？"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="rollBackCustomerMaterial(item)"
                    class="left_icon"
                  >
                    <a-icon class="customer_icon" type="close" />
                  </a-popconfirm>
                  <a-popconfirm
                    title="确认保存吗？"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="saveCustomerMaterial(item)"
                    class="left_icon"
                  >
                    <a-icon class="customer_icon" style="margin-left: 20px" type="check" />
                  </a-popconfirm>
                </div>
              </div>
            </span>
          </a-list-item-meta>
        </a-list-item>
      </a-list>
    </a-spin>

    <MultiUploadProduce
      ref="multiUploadProduce"
      :applyid="applyid"
      :busiType="busiType"
      :currentUser="currentUser"
      @afterUpload="queryMaterialsList"
    ></MultiUploadProduce>

    <MaterialVersion ref="materialVersionRef"></MaterialVersion>

    <CaseDecisionIntervene
      ref="CaseDecisionIntervene"
      :faapplyid="applyid"
      :isMain="true"
      :isFlow="false"
      @submit="startBusinessProcedClick"
    ></CaseDecisionIntervene>
    <!-- <component
      ref="component"
      :is="component"
      :applyid="applyid"
      :proctype="busiName"
      :busiType="busiType"
      :decisionType="decisiontype"
      :fileItem="fileItem"
      :processinstanceid="processinstanceid"
      @reload="reloadComponent"
      @gotoSonRouter="autoToSonRouter" />

    <component
      ref="updateComponent"
      :is="updateComponent"
      :applyid="applyid"
      :busiType="busiType"
      :decisionType="decisiontype"
      :materialOption="selectedOption"
      @reload="reloadComponent" /> -->
  </a-card>
</template>
<script>
import { getAllMaterialByApplyId } from '@/api/accept/aprv_process_materials'
import { queryCustomerMaterialByApplyid } from '@/api/accept/aprv_materials_customer'
import { getTabByCategory } from '@/enumeration/Tp_category'
import { Tp_proctypeValue, Tp_proctypeEnum } from '@/enumeration/Tp_proctype'
import {
  Tp_procmaterialValue,
  Tp_procmaterial_decision_termediate,
  Tp_procmaterial_decision_listen,
  Tp_procmaterial_decision_descion,
  Tp_procmaterial_decision_asynapprove
} from '@/enumeration/Tp_procmaterial'
import { Tp_decisionValue, Tp_decision } from '@/enumeration/Tp_decision'
import { startBusinessProced } from '@/api/accept/business_Approve'
import { ProcedureMinxin } from '../ProcedureMinxin'
import { getDecisionTypeTree } from '@/api/accept/apl_decistiontype'
import { updatesIscitymanager } from '@/api/accept/apl_admre_audit'
import { passRecordExecute } from '@/api/accept/process_approve.js'
import { getReviewById } from '@/api/accept/apl_admreview.js'
import { changeDecisionType } from '@/api/accept/business_Approve'
import { Tp_apptypeValue } from '@/enumeration/Tp_apptype.js'
// 默认当前的类型是决定类型
const currentProctype = Tp_proctypeValue.HEAR_DECISION
export default {
  mixins: [ProcedureMinxin],
  components: {
    CaseDecisionIntervene: () => import('@/views/handleCase/accept/CaseDecisionIntervene')
  },
  data () {
    return {
      selectKey: undefined,
      options: [],
      tabActive: '',
      currentSonstatus: undefined, // 当前子流程状态
      Tp_decisionValue: Tp_decisionValue,
      admReviewObj: {}, // 行政复议对象
      isCitymanager: null, // 是否市领导审批
      selectRoot: {}, // 选中的节点的根节点
      selectRootName: '', // 选中的节点的根节点名称
      rootNodeObj: {}, // 根级节点隐射对象
      colorNodeObj: [], // 颜色色块映射对象
      spanColor: '#01d6d0',
      selectBtnShow: undefined // 业务选择按钮
    }
  },
  watch: {
    selectKey: {
      // value 需要深度监听及默认先执行handler函数
      handler (val) {
        if (val) {
          const currentNode = this.findNodeById(this.selectKey, this.options)
          const rootNodeId = this.rootNodeObj[this.selectKey]
          const rootNode = this.findNodeById(rootNodeId, this.options)
          let parentName = ''
          if (rootNode) {
            this.colorNodeObj.forEach(el => {
              if (rootNode.parentid && el.id == rootNode.parentid) {
                parentName = el.name
                this.spanColor = el.color
              }
            })
          }
          parentName = parentName != '' ? parentName + '-' : ''
          if (currentNode.level > 3) {
            const secondRootNode = this.findNodeById(currentNode.parentid, this.options)
            this.selectRootName = '【' + parentName + rootNode.name + '】' + '-' + '【' + secondRootNode.name + '】'
          } else {
            if (rootNode) {
              this.selectRootName = '【' + parentName + rootNode.name + '】'
            } else {
              this.selectRootName = '【' + parentName + currentNode.name + '】'
            }
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  async created () {
    const _this = this
    console.log('busikey' + this.busiKey)
    this.initBusiType()
    await this.getSelectTreeData()
    // 判断当前是子流程还是主流程
    await this.setIsMainProcess()
    this.initParam()
    this.queryMaterialsList()
    if (this.sonStatus != undefined && this.sonStatus != null && this.sonStatus.length > 0) {
      _this.currentSonstatus = undefined
      this.currentSonstatus = this.sonStatus.filter(item => item == this.busiName)[0]
    } else {
      this.currentSonstatus = undefined
    }
  },
  mounted () {},
  methods: {
    initCaseInterven () {
      this.$refs.CaseDecisionIntervene.init()
    },
    async initBusiType () {
      // 通过传入的类型来获取对应的数据
      this.typeEnum = {}
      // 决定类型
      this.typeEnum = this.Tp_proctypeEnum.hear_decision
      this.labelTitle = this.typeEnum.name
      this.busiType = this.typeEnum.value
      this.busiName = this.typeEnum.key
      const res = await getReviewById(this.applyid)
      if (res.code == 0) {
        this.admReviewObj = res.data
      } else {
        this.admReviewObj = {}
        this.$message.error('查询行政复议数据失败')
      }
      this.setButtonDisabled()
    },
    initParam () {
      // 通过传入的类型来获取对应的数据
      // this.typeEnum = {}
      // // 决定类型
      // this.typeEnum = this.Tp_proctypeEnum.hear_decision
      // this.labelTitle = this.typeEnum.name
      // this.busiType = this.typeEnum.value
      // this.busiName = this.typeEnum.key60049027
      // this.setButtonDisabled()
      if (this.decisiontype != null && this.decisiontype != undefined) {
        this.selectKey = this.decisiontype
      } else {
        this.selectKey = undefined
      }
      this.selectChange(this.selectKey, true)
      this.initComponent()
    },
    initComponent () {
      // 后续调整
      // let tabActive = 'CaseHandleDecisionBasic'
      // // 驳回复议申请 和 驳回复议请求- 《驳回行政复议申请决定书》
      // if (this.selectKey == Tp_decisionValue.PROREJECT || this.selectKey == Tp_decisionValue.SUBREJECT) {
      //   tabActive = 'CaseHandleDecisionReject'
      // }
      // // 维持, 确认违法, 变更, 责令履行, 其它 -《行政复议决定书》
      // if (
      //   this.selectKey == Tp_decisionValue.MAINTAIN ||
      //   this.selectKey == Tp_decisionValue.BREAKLAW ||
      //   this.selectKey == Tp_decisionValue.CHANGE ||
      //   this.selectKey == Tp_decisionValue.ORDER ||
      //   this.selectKey == Tp_decisionValue.OTHER
      // ) {
      //   tabActive = 'CaseHandleDecisionConsider'
      // }
      // 撤销 -《撤回行政复议申请书》  终止-调解  -《行政复议调解书》《行政复议和解书》
      // if (this.selectKey == Tp_decisionValue.REVOKE || this.selectKey == Tp_decisionValue.TERMEDIATE) {
      //   let tabActive = 'CaseHandleDecisionBasic'
      //   this.component = () => import(`@/views/handleCase/accept/${tabActive}`)
      //   this.updateComponent = () => import('@/views/handleCase/base/component/BaseCaseHandleUpdate')
      //   return
      // }
      // // 终止-其它  《行政复议终止决定书》
      // if (this.selectKey == Tp_decisionValue.TEROTHER) {
      //   tabActive = 'CaseHandleDecisionTerminate'
      // }
      // this.tabActive = tabActive
      // this.component = () => import(`@/views/handleCase/accept/${tabActive}`)
      // this.component = () => import('@/views/handleCase/base/component/BaseCaseHandle')
      // this.updateComponent = () => import('@/views/handleCase/base/component/BaseCaseHandleUpdate')
    },
    // 获取节点中含有value的所有key集合
    getkeyList (value, tree, keyList) {
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        node.scopedSlots = { title: 'name' }
        if (node.name.indexOf(value) > -1) {
          keyList.push(node.code)
        }
        if (node.children) {
          this.getkeyList(value, node.children, keyList)
        }
      }
      return keyList
    },

    // 该递归主要用于获取key的父亲节点的key值
    getParentKey (key, tree) {
      let parentKey, temp
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]

        if (node.children) {
          if (node.children.some(item => item.code === key)) {
            parentKey = node.code
          } else if ((temp = this.getParentKey(key, node.children))) {
            parentKey = temp
          }
        }
      }
      return parentKey
    },
    // 获取该节点的所有祖先节点
    getAllParentKey (key, tree) {
      var parentKey
      if (key) {
        parentKey = this.getParentKey(key, tree)
        if (parentKey) {
          if (!this.backupsExpandedKeys.some(item => item === parentKey)) {
            this.backupsExpandedKeys.push(parentKey)
          }
          this.getAllParentKey(parentKey, tree)
        }
      }
    },

    setDisabled (treeData) {
      treeData.forEach(tree => {
        if (tree.children && tree.children.length > 0) {
          tree.disabled = true
          this.setDisabled(tree.children)
        }
      })
    },
    setRootTree (rootNodeId, treeData) {
      treeData.forEach(tree => {
        if (tree.children && tree.children.length > 0) {
          this.setRootTree(rootNodeId, tree.children)
        } else {
          this.rootNodeObj[tree.id] = rootNodeId
        }
      })
    },
    setRootTreeMap (treeData) {
      treeData.forEach(tree => {
        this.setRootTree(tree.id, tree.children)
      })
    },
    // async getReviewById () {
    //   const res = await getReviewById(this.applyid)
    //   if (res.code == 0) {
    //     this.admReviewObj = res.data
    //     debugger
    //     this.isCitymanager = this.admReviewObj.iscitymanager ? this.admReviewObj.iscitymanager : 3201
    //   } else {
    //     this.$message.error('查询行政复议数据失败')
    //   }
    // },
    // citymanagerChange (e) {
    //   this.isCitymanager = e.target.value
    //   updatesIscitymanager(this.applyid, this.isCitymanager).then((res) => {
    //     if (res.code !== 0) {
    //       console.log('更新是否市领导审批字段失败')
    //     } else {
    //       console.log('更新是否市领导审批字段成功')
    //       this.selectChange(this.selectKey, true)
    //     }
    //   })
    // },
    async getSelectTreeData () {
      const res = await getDecisionTypeTree()
      if (res.code == 0) {
        const decistionTypeTree = res.data
        // 去除第一层级的节点
        let newOptions = []
        this.colorNodeObj = []
        decistionTypeTree.forEach(el => {
          const obj = {
            id: el.id,
            name: el.name,
            color: ''
          }
          if (el.name == '维持和驳回') {
            obj.color = '#01d6d0'
          } else if (el.name == '直接纠错') {
            obj.color = '#0ba8fe'
          } else {
            obj.color = '#973621'
          }
          this.colorNodeObj.push(obj)
          newOptions = newOptions.concat(el.children)
        })
        // 进行设置，父节点无法选择
        this.setDisabled(newOptions)
        // 选择出二级节点
        this.setRootTreeMap(newOptions)
        this.options = newOptions
      } else {
        this.$message.error('查询复议决定类型失败')
      }
    },
    setButtonDisabled () {
      if (this.isEditModel) {
        const tabCategory = getTabByCategory(this.category, this.busiKey)
        if (tabCategory == 'editAll') {
          this.operateBtnShow = true // 操作按钮展示
          this.uploadBtnShow = true // 上传按钮展示
        } else if (tabCategory == 'disabled') {
          this.operateBtnShow = false
          this.uploadBtnShow = true
        } else if (tabCategory == 'editOnlySelf') {
          this.operateBtnShow = false
          this.uploadBtnShow = true
        }
        // 判断是否是在启用的子流程，若是则需要隐藏提交按钮
        if (this.sonStatus.includes(this.busiName)) {
          this.operateBtnShow = false
        }
      } else {
        this.operateBtnShow = false
        this.uploadBtnShow = false
      }
      this.selectBtnShow = this.operateBtnShow
      // FIXME: 临时放开
      this.uploadBtnShow = true
      if (this.admReviewObj && this.admReviewObj.hearfirstid) {
        if (
          this.admReviewObj.hearfirstid == this.currentUser.userId ||
          this.admReviewObj.hearsecondid == this.currentUser.userId
        ) {
          this.selectBtnShow = true
        }
      }
    },
    findNodeById (id, data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].id === id) {
          return data[i]
        } else if (data[i].children && data[i].children.length > 0) {
          const result = this.findNodeById(id, data[i].children)
          if (result) {
            return result
          }
        }
      }
      return null
    },
    /**
     * 修改被申请人
     * @param {} e
     */
    citymanagerChange (e) {
      this.isCitymanager = e.target.value
      if (!this.isMainProcess) {
        updatesIscitymanager(this.applyid, this.isCitymanager).then(res => {
          if (res.code !== 0) {
            console.log('更新是否市领导审批字段失败')
          } else {
            console.log('更新是否市领导审批字段成功')
            this.selectChange(this.selectKey, true)
          }
        })
      } else {
        this.selectChange(this.selectKey, true)
      }
    },

    async selectChange (value, forceReload) {
      let _this = this
      const material = []
      this.fileItem = []
      // 除了调解，其他所有决定类型都是行政复议决定书
      const selectNode = _this.findNodeById(value, this.options)
      if (selectNode) {
        // 新增听取意见材料项
        // 判断当时是普通程序还是简易程序，若是普通程序则不进行校验
        // 简易程序不展示听证调查表
        if (this.admReviewObj.proctype == Tp_apptypeValue.ORDINARY) {
          material.push(Tp_procmaterial_decision_listen['hear_listen'])
        }
        if (selectNode.name.indexOf('行政复议调解') > -1) {
          material.push(Tp_procmaterial_decision_termediate['hear_mediate'])
        } else {
          const rootNodeId = this.rootNodeObj[value]
          const rootNode = this.findNodeById(rootNodeId, this.options)
          for (const key in Tp_procmaterial_decision_descion) {
            console.log('结果', Tp_procmaterial_decision_descion[key])
            if (Tp_procmaterial_decision_descion[key].value == rootNode.materialtype) {
              material.push(Tp_procmaterial_decision_descion[key])
            }
          }
        }
      } else {
        material.push(Tp_procmaterial_decision_descion['hear_decision'])
      }
      if (this.isCitymanager == 3200) {
        // 需要
        material.push(Tp_procmaterial_decision_asynapprove['hear_asynapprove'])
      }
      if (material) {
        for (const index in material) {
          if (material[index]) {
            const fileItem = {
              fileName: material[index].name,
              fileType: material[index].value,
              isMultiUpload: true,
              fileList: [],
              required: material[index].required,
              isCustomer: false,
              isSaved: true,
              isUpdated: false
            }
            this.fileItem.push(fileItem)
          }
        }
      }
      // 查询当前的决定阶段的自定义材料
      if (forceReload) {
        const res = await queryCustomerMaterialByApplyid({ applyid: this.applyid })
        if (res.code == 0) {
          const customerMaterials = res.data
          // 只过滤当前步骤为决定步骤的的自定义材料
          this.customerMaterials = customerMaterials.filter(item => item.proctype == currentProctype)
        } else {
          console.log('查询自定义材料错误...')
        }
      }
      // 查询对应applyid的表单生成材料类型
      this.queryMaterialOptionList()
      for (const index in this.customerMaterials) {
        // 过滤当前的决定类型的自定义材料
        const customerFileItem = {
          fileName: this.customerMaterials[index].name,
          fileType: Tp_procmaterialValue.MATER_CUSTOMER,
          replyCustomerId: this.customerMaterials[index].id,
          isMultiUpload: true,
          fileList: [],
          required: false,
          isCustomer: true,
          isSaved: true,
          isUpdated: false,
          sortnum: this.customerMaterials[index].sortnum
        }
        this.fileItem.push(customerFileItem)
      }
      this.filteFile(currentProctype)
      this.initComponent()
    },
    /**
     * 查询对应的applyid下有多少材料文件
     */
    queryMaterialsList () {
      this.queryParam.applyid = this.applyid
      this.spinning = true
      getAllMaterialByApplyId(this.queryParam)
        .then(res => {
          // console.log('表格数据:', res.data)
          const records = res.data
          this.allFileList = records
          this.filteFile(currentProctype)
        })
        .catch(err => {
          console.log(err, '获取数据失败')
        })
        .finally(() => {
          this.spinning = false
        })
    },
    reloadComponent () {
      // 查询对应applyid的表单生成材料类型
      this.queryMaterialOptionList()
      this.queryMaterialsList()
    },

    startBusinessProcedClick (recordId) {
      let rootNodeId = this.rootNodeObj[this.selectKey]
      let rootNode = this.findNodeById(rootNodeId, this.options)
      const currentNode = this.findNodeById(this.selectKey, this.options)
      if (!currentNode) {
        this.$message.warning('请选择决定类型')
        return
      }
      if (!rootNode) {
        rootNode = currentNode
        rootNodeId = currentNode.id
      }
      let title = '是否发起决定-' + rootNode.name + '审批？'
      if (this.selectKey == null || this.selectKey == undefined || rootNode == null || rootNode == undefined) {
        this.$message.warning('请选择决定类型')
        return
      } else if (this.sonStatus != null && this.sonStatus != undefined && this.sonStatus.length > 0) {
        title = '当前正在审批中的步骤有：'
        const sonStatusName = []
        this.sonStatus.forEach(son => {
          sonStatusName.push('【' + Tp_proctypeEnum[son].name + '】')
        })
        title = title + sonStatusName.join(',') + ', 是否发起决定-' + rootNode.name + '审批？'
      }
      this.$confirm({
        title: title,
        okText: '确定',
        cancelText: '取消',
        zIndex: 2001,
        onOk: () => {
          this.startBusinessProced(this.busiName, rootNode.name, rootNodeId, currentNode, recordId)
        }
      })
    },

    startBusinessProced (busiName, describe, rootNodeId, currentNode, recordId) {
      passRecordExecute(this.applyid, this.typeEnum.categoryKey).then(res => {
        if (res.data.code != 0) {
          this.$message.warning(res.data.msg)
          return
        } else {
          // 启动流程
          const flowParams = {
            applyid: this.applyid, // applyid
            proctype: busiName, // 操作分类
            userid: this.currentUser.userId,
            username: this.currentUser.fullname,
            processinstanceid: this.processinstanceid, // 流程实例id
            cause: '', // 案由
            describe: describe + '申请'
          }
          const docfield = {
            isCitymanager: this.isCitymanager,
            decisiontype: rootNodeId,
            decisiontypeid: currentNode.id,
            decisiontypename: currentNode.name,
            recordId: recordId
          }
          this.processLoading = true
          console.log('流程入参', flowParams)
          startBusinessProced(flowParams, docfield)
            .then(res => {
              if (res.code !== 0) {
                this.$message.error('操作失败')
              } else {
                this.$message.success('操作成功')
                this.$emit('reload')
                this.$emit('close')
                this.modalVisible = false
                // 暂时隐藏流程跳转
                this.autoToSonRouter(res.data, busiName)
              }
            })
            .finally(() => {
              this.processLoading = false
            })
        }
      })
    },

    activeBtnClick () {
      const _this = this
      if (this.selectKey == null || this.selectKey == undefined) {
        this.$message.warning('请选择决定类型')
      } else if (this.sonStatus != null && this.sonStatus != undefined && this.sonStatus.length > 0) {
        let title = '当前正在审批中的步骤有：'
        const sonStatusName = []
        this.sonStatus.forEach(son => {
          sonStatusName.push('【' + Tp_proctypeEnum[son].name + '】')
        })
        title = title + sonStatusName.join(',') + ', 是否发起决定审批？'
        this.$confirm({
          title: title,
          okText: '确定',
          cancelText: '取消',
          zIndex: 2001,
          onOk: () => {
            _this.$refs.component.init(this.tabActive)
          }
        })
      } else {
        this.$refs.component.init(this.tabActive)
      }
    },

    changeDecisionType () {
      let rootNodeId = this.rootNodeObj[this.selectKey]
      let rootNode = this.findNodeById(rootNodeId, this.options)
      const currentNode = this.findNodeById(this.selectKey, this.options)
      if (!rootNode) {
        rootNode = currentNode
        rootNodeId = currentNode.id
      }
      this.$confirm({
        title: '是否重新选择决定类型？',
        okText: '确定',
        cancelText: '取消',
        zIndex: 2001,
        onOk: () => {
          this.processLoading = true
          changeDecisionType(
            this.$route.params.faapplyid,
            this.$route.params.applyid,
            rootNodeId,
            currentNode.id,
            currentNode.name
          )
            .then(res => {
              if (res.code !== 0) {
                this.$message.error('操作失败')
              } else {
                this.$message.success('操作成功')
                this.$emit('reload')
              }
            })
            .finally(() => {
              this.processLoading = false
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/apply/caseProcedure.scss';

.case_produce {
  //  ::v-deep .ant-cascader-menu {
  //    max-width: 320px !important;
  //  }
  ::v-deep .ant-cascader-menu {
    max-width: 320px !important;
  }
}
.transparent-input {
  background-color: transparent; /* 设置背景透明 */
  border: none; /* 移除边框 */
  border-bottom: 1px solid rgb(251, 251, 252); /* 可选：添加底部边框以提升可视度 */
  outline: none; /* 移除默认的输入框外观 */
  color: rgb(119, 166, 253); /* 设置文本颜色 */
  /* 可以根据需要添加更多样式 */
}
.upload_list_div {
  margin-left: 15px !important;
}
</style>
